using System;
using System.Collections.Generic;
using Kotonoha.Server.Core.Utils;
using Kotonoha.Server.Db.Dao;
using Kotonoha.Server.Objects.Model;
using Kotonoha.Server.Dictionaries;

using System.Linq;

namespace Kotonoha.Server.Model {
    public static class KanjiFactory {
        //Unicode ranges of characters
        private static readonly int[] ranges = new[] {
                                                  0x4e00, 0x9fff, //CJK Unified Ideographs
                                                  0x3400, 0x4dbf, //CJK Unified Ideographs Extension A
                                                  0x20000, 0x2a6df //CJK Unified Ideographs Extension B
                                              };

        public static Kanji create(string ch) {
            DictDao dao = new DictDao(HibernateUtil.Instance.Session);
            CharEntry c = dao.findChar(ch);
            Kanji k = new Kanji();
            k.AddedDate = DateTime.Now;
            k.Character = ch;
            k.Kunyomis = c.Kunyomi.ToArray();
            k.Onyomis = c.Onyomi.ToArray();
            k.Meanings = c.Meanings.ToArray();
            k.Strokes = c.Strokes;
            return k;
        }

        public static IEnumerable<Kanji> createAll(string s) {
            return findKanji(s).Select(ks => create(ks));
        }

        public static IEnumerable<string> findKanji(string s) {
            int size = ranges.Length / 2;
            for (int i = 0; i < s.Length; ++i) {
                string ch;
                if (char.IsSurrogatePair(s, i)) {
                    ch = s.Substring(i, 2);
                    ++i;
                } else {
                    ch = s.Substring(i, 1);
                }
                int utf32 = char.ConvertToUtf32(ch, 0);

                for (int j = 0; j < size; j += 2) {
                    if (utf32 >= ranges[j] && utf32 <= ranges[j + 1]) {
                        yield return ch;
                    }
                }
            }
        }
    }
}